package seismosurfer.servlets.util;

import java.util.List;
import java.util.Properties;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import seismosurfer.database.DB;
import seismosurfer.update.UpdateService;
import seismosurfer.util.Registry;

import com.bbn.openmap.util.Debug;
import com.bbn.openmap.util.PropUtils;

/**
 * A ServletContextListener that handles
 * initialization tasks when the web application starts.
 *
 */
public class ApplicationListener implements ServletContextListener {
    // Notification that the web application is ready to process requests
    public void contextInitialized(ServletContextEvent sce) {

        SessionHandler.setServletContext(sce.getServletContext());
        initDebug();
        DB.init();

        if (beginUpdate()) {
            new UpdateService();
        }

        SessionHandler.setGoogleMapsKey();

        new Cache(gerRowNum());
    }

    private int gerRowNum() {
        Properties p = Registry.getOpenmapProperties();
        int result = PropUtils.intFromProperties(p, "seismosurfer.top.rownum",
                5);
        return result;
    }

    private boolean beginUpdate() {
        Properties p = Registry.getOpenmapProperties();
        return PropUtils.booleanFromProperties(p, "seismosurfer.update.start",
                false);
    }

    private void initDebug() {

        Properties p = Registry.getOpenmapProperties();

        String debug = p.getProperty("openmap.Debug");
        Debug.output(debug);

        List keywords = PropUtils.parseSpacedMarkers(debug);

        for (int i = 0; i < keywords.size(); i++) {
            String keyword = (String) keywords.get(i);

            if (keyword.equalsIgnoreCase(Debug.debugAllToken)) {
                Debug.debugAll = true;
            }
            Debug.put(keyword);

            Debug.output(keyword);
        }
    }

    // Notification that the servlet context is about to be shut down
    public void contextDestroyed(ServletContextEvent sce) {
    }
}